#
# Package.
#

package iSOCK::Model::BZC;

#
# Base.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Model' }

#
# Dependencies.
#

use BZ::Client; # FIXME 1.04_01
use BZ::Client::Bug;
use Try::Tiny;

#
# Subs.
#

sub issues {
  my ( $self, $name, $version, $c, $tracker_r ) = @_;
  
  my $url = $tracker_r->url;
  
  if ( my $bz = BZ::Client->new ( url => $url, user => $tracker_r->login, password => $tracker_r->password ) ) {
    my @issues;

    try {
      if ( my $bug_ids = BZ::Client::Bug->search ( $bz, { product => $name, component => 'Documentation' } ) ) { # FIXME $tracker_r->component == 'Documentation'?
        for ( @$bug_ids ) {
          my $hash = {
            created_on => $_->creation_time->iso8601,
            issue_id   => $_->id,
            issue_url  => "$url/show_bug.cgi?id=" . $_->id,
            name       => $_->product,
            owner      => $_->assigned_to,
            requestor  => $_->{creator},
            status     => $_->status,
            resolution => $_->resolution,
            summary    => $_->summary || $_->{description},
            version    => $version,
          };

          if ( $hash->{status} eq 'RESOLVED' ) {
            $hash->{closed_on} = $_->last_change_time->iso8601;
          }

          push @issues, $hash; # description: N/A
        }
      }
    }
    catch {
      if ( ref eq 'BZ::Client::Exception' ) {
        $c->log->error ( $_->message ); # https://metacpan.org/module/BZ::Client::Exception => ( message, http_code, xmlrpc_code )
      }
      else {
        $c->log->error ( $_ );
      }
    };

    if ( scalar @issues ) {
      return \@issues;
    }
  }
  
  return;
}

#
# True.
#

1;
